package com.orange.notificationsummary.event.pil.defaultimpl;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.Settings;
import android.provider.Settings.System;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.orange.homescreen.pil.DateTimeInterface;
import com.orange.homescreen.pil.PILInterfaceManager;
import com.orange.notificationsummary.R;
import com.orange.notificationsummary.utils.Constants.EventType;
import com.orange.notificationsummary.utils.EventLSWidgetUtils;
import com.orange.notificationsummary.utils.LogHelper;
import com.orange.notificationsummary.utils.NtfcUtils;
import com.orange.notificationsummary.utils.VipUtils;

public abstract class BaseEvent implements OnClickListener,
		Comparable<BaseEvent> {
	private static final String	TAG					= "BaseEvent";

	public int					id;
	public Drawable				event_type_image;
	public String				event_type_name;
	public long					threadId			= 0;
	public long					event_date;
	public String				evnet_number;
	public String				evnet_number_type;
	public String				evnet_name;
	// public String event_content;
	public int					event_type;

	public String				event_mmssubject_smscontent;
	public String				event_mms_subject;
	public String				event_mms_content;
	public String				event_sms_content;

	public String				threads_recipient;

	public Bitmap				contacts_image		= null;
	public Bitmap				mms_one_image		= null;

	public String				contacts_id;
	public long					callLogId;
	public boolean				isVip;
	public boolean				isInContacts;
	public boolean				isInMMSImage;
	public int					phoneNumberCount	= 0;
	public Context				context;

	protected RelativeLayout	mLayout;
	protected ImageView			mContact_image;
	protected ImageView			mVip_image;
	protected ImageView			mEvent_type_images;
	protected TextView			mName;
	protected TextView			mData;
	protected TextView			mFrom;
	protected ImageView			mAttIcon;
	// protected TextView content;
	protected Resources			mResources;

	private TextView			mmsSubject;
	private TextView			mmsContent;
	private TextView			smsContent;

	protected int				mLayoutWidth;
	protected int				mLayoutHeight;

	public boolean				isAttVisible;

	private static final String	UNKNOWN_NUMBER		= "-";

	public BaseEvent(Context context) {
		this.context = context;
		mResources = context.getResources();
	}

	protected abstract void setContactPicture();

	public abstract void lookDetail();

	public abstract void showCallDialog();

	public abstract void showMsgDialog();

	public abstract void showContactDialog();

	public View getView(final Context context, View v) {
		mLayout = (RelativeLayout) v.findViewById(R.id.image_layout);
		mContact_image = (ImageView) v.findViewById(R.id.contact_image);
		mContact_image.setOnClickListener(this);
		mVip_image = (ImageView) v.findViewById(R.id.vip_image);
		mEvent_type_images = (ImageView) v.findViewById(R.id.event_type_image);
		mName = (TextView) v.findViewById(R.id.event_type_name);
		mData = (TextView) v.findViewById(R.id.event_type_date);
		mFrom = (TextView) v.findViewById(R.id.event_comefrom);
		mAttIcon = (ImageView) v.findViewById(R.id.ns_mms_attachement_icon);

		mmsSubject = (TextView) v.findViewById(R.id.event_mms_subject);
		mmsContent = (TextView) v.findViewById(R.id.event_mms_description);
		smsContent = (TextView) v.findViewById(R.id.event_sms_description);

		mName.setText("");
		mData.setText("");
		mFrom.setText("");
		mmsSubject.setText("");
		mmsContent.setText("");
		smsContent.setText("");

		if (isVip) {
			mVip_image.setVisibility(View.VISIBLE);
		} else {
			mVip_image.setVisibility(View.INVISIBLE);
		}

		setContactPicture();
		if (event_type_image != null) {
			mEvent_type_images.setBackgroundDrawable(event_type_image);
		}

		if (event_type_name != null && getFmtDate(context) != null) {
			mName.setText(event_type_name + ",");
		}
		// data.setText(getFmtDate(context));
		// modify by gaoge 2011-08-29 for fix bug 0013261
		mData.setText(EventLSWidgetUtils.dateFormat(context, event_date));

		String number = getFromNumber(evnet_name, phoneNumberCount);
		mFrom.setText(number);

		setMmsSmsContent();

		if (isAttVisible) {
			mAttIcon.setVisibility(View.VISIBLE);
		} else {
			mAttIcon.setVisibility(View.GONE);
		}

		return v;
	}

	private String getFromNumber(String eventName, int phoneNumberCount) {
		String fromName = context.getResources().getString(R.string.from);
		String tempName = null;

		if (evnet_name != null) {
			if (phoneNumberCount > 1) {
				tempName = fromName + " " + evnet_name + " "
						+ evnet_number_type;
			} else {
				tempName = fromName + " " + evnet_name;
			}
		} else {
			if (evnet_number.startsWith(UNKNOWN_NUMBER)
					|| evnet_number.equalsIgnoreCase("unknown")
					|| evnet_number.equalsIgnoreCase("blocked")) {
				tempName = fromName + " "
						+ context.getString(R.string.from_unknown);
			} else {
				tempName = fromName + " " + evnet_number;
			}
		}

		return tempName;
	}

	private void setMmsSmsContent() {
		if (event_type == EventType.VVM_UPDATE) {
			if (!TextUtils.isEmpty(event_mmssubject_smscontent)) {
				mmsSubject.setVisibility(View.GONE);
				mmsContent.setVisibility(View.GONE);

				smsContent.setVisibility(View.VISIBLE);
				smsContent.setText(event_mmssubject_smscontent);
			}
		} else if (event_type == EventType.UNMSG_UPDATE) {
			//modify by gaoge for fix bug 0014249
			if ((TextUtils.isEmpty(event_sms_content) || event_sms_content.equals(" "))
//			if ((TextUtils.isEmpty(event_sms_content))
					&& TextUtils.isEmpty(event_mms_subject)
					&& TextUtils.isEmpty(event_mms_content)) {
				mmsSubject.setVisibility(View.GONE);
				mmsContent.setVisibility(View.GONE);

				smsContent.setVisibility(View.VISIBLE);
				smsContent.setText(context.getString(R.string.no_message));
			} else if (!TextUtils.isEmpty(event_sms_content)
					&& TextUtils.isEmpty(event_mms_subject)
					&& TextUtils.isEmpty(event_mms_content)) {
				mmsSubject.setVisibility(View.GONE);
				mmsContent.setVisibility(View.GONE);

				smsContent.setVisibility(View.VISIBLE);
				smsContent.setText(event_sms_content);
			} else if (TextUtils.isEmpty(event_sms_content)
					&& !TextUtils.isEmpty(event_mms_subject)
					&& TextUtils.isEmpty(event_mms_content)) {
				mmsContent.setVisibility(View.GONE);
				smsContent.setVisibility(View.GONE);

				mmsSubject.setVisibility(View.VISIBLE);
				mmsSubject.setText(event_mms_subject);
			} else if (TextUtils.isEmpty(event_sms_content)
					&& TextUtils.isEmpty(event_mms_subject)
					&& !TextUtils.isEmpty(event_mms_content)) {
				mmsSubject.setVisibility(View.GONE);
				smsContent.setVisibility(View.GONE);

				mmsContent.setMaxLines(2);
				mmsContent.setVisibility(View.VISIBLE);
				mmsContent.setText(event_mms_content);
			} else if (TextUtils.isEmpty(event_sms_content)
					&& !TextUtils.isEmpty(event_mms_subject)
					&& !TextUtils.isEmpty(event_mms_content)) {
				smsContent.setVisibility(View.GONE);
				mmsSubject.setVisibility(View.VISIBLE);
				mmsContent.setVisibility(View.VISIBLE);

				mmsSubject.setText(event_mms_subject);
				mmsContent.setSingleLine();
				mmsContent.setText(event_mms_content);
			}
		}
	}

	private String getFmtDate(Context context) {
		String formatted = null;
		DateTimeInterface interfc = (DateTimeInterface) PILInterfaceManager
				.getInterface(DateTimeInterface.class);

		String time = interfc.getSystemFormattedTime(context, event_date);

		if (time.substring(0, 2).equalsIgnoreCase("24")) {
			time = "00" + time.substring(2, time.length());
		}

		if (interfc.isToday(event_date)) {
			String today = context.getString(R.string.today);

			if (today == null) {
				today = "Today";
			}

			formatted = String.format("%s %s", today, time);
		} else if (interfc.isInThisYear(event_date)) {
			formatted = interfc.getFormattedDate(getDataFormat(context, false),
					event_date);
			formatted = formatted + ", " + time;
		} else {
			formatted = interfc.getFormattedDate(getDataFormat(context, true),
					event_date);
			formatted = formatted + ", " + time;
		}

		return (formatted == null ? "" : formatted);
	}

	// public static String getDayOfWeek(Context context,long milliseconds){
	// Calendar calendar = Calendar.getInstance();
	// calendar.setTimeInMillis(milliseconds);
	// int mDayOfWeek = calendar.get((Calendar.DAY_OF_WEEK))-1;
	// return
	// context.getResources().getString(EventLSWidgetUtils.dayOfWeek[mDayOfWeek]);
	// }

	public static String getDataFormat(Context context, Boolean year) {
		String dateFormat = Settings.System.getString(
				context.getContentResolver(), System.DATE_FORMAT);
		boolean b = true;
		if (dateFormat == null) {
			dateFormat = "MMM dd";
		}
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < dateFormat.length(); i++) {
			char a = dateFormat.charAt(i);

			if (year && 'y' == a) {
				buffer.append(a);
			} else if ('-' == a) {
				buffer.append(' ');
			} else if ('M' == a) {
				if (b) {
					buffer.append("MM");
					b = false;
				} else {
					buffer.append(a);
				}
			} else if ('d' == a) {
				buffer.append(a);
			}
		}
		return buffer.toString().trim();
	}

	@Override
	public void onClick(View v) {
		if (isVip) {
			VipUtils.startVipActivity(context, contacts_id);
		} else if (!isVip && isInContacts) {
			Uri lookup = Contacts.getLookupUri(
					context.getContentResolver(),
					ContentUris.withAppendedId(Contacts.CONTENT_URI,
							Long.parseLong(contacts_id)));
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setData(lookup);
			NtfcUtils.startActivity(context, i);
		} else if (!isVip && isInMMSImage) {
			startSlideShowActivity();
		} else {
			showDialog();
		}
	}

	private void startSlideShowActivity() {
		// Launch the slideshow activity to play/view.
		String selection = new String("mid='" + id + "'");
		Cursor cursor = context.getContentResolver().query(
				Uri.parse("content://mms/part"), null, selection, null, null);
		int _partID = 0;
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				_partID = cursor.getInt(cursor.getColumnIndex("_id"));
			}
			cursor.close();
		}

		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		Uri partURI = Uri.parse("content://mms/part/" + (_partID + 1));
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.setDataAndType(partURI, "image/*");
		NtfcUtils.startActivity(context, intent);
	}

	private void showDialog() {
		String call = context.getResources().getString(R.string.call);
		String sendMsg = context.getResources().getString(
				R.string.sendTextMessage);
		String addContact = context.getResources().getString(
				R.string.addToContact);
		final CharSequence[] items = { call + " " + evnet_number, sendMsg,
				addContact };
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(evnet_number);
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				switch (item) {
				case 0:
					showCallDialog();
					break;
				case 1:
					showMsgDialog();
					break;
				case 2:
					showContactDialog();
					break;
				default:
					break;
				}
			}
		});
		builder.show();
	}

	@Override
	public int compareTo(BaseEvent another) {
		long time = another.event_date;
		if (time > event_date) {
			return 1;
		} else if (time < event_date) {
			return -1;
		} else {
			return 0;
		}
	}
}
